import os
import time
import logging
import win32com.client


# 配置参数
RETRY_TIMES = 3  # 最大重试次数
DELAY_SECONDS = 7  # 默认延迟时间（秒）
Port = 4370
Enabled = 1  # 用户启用标志：1为启用

current_dir = os.path.dirname(os.path.abspath(__file__))
target_dir = os.path.join(os.path.dirname(current_dir), "logs")  # 子目录名称
log_filename = os.path.join(target_dir, "attendance_record.log")
logging.basicConfig(
    level=logging.INFO,  # 设置日志级别为INFO
    format='%(asctime)s - %(levelname)s - %(message)s',  # 设置日志格式
    handlers=[
        logging.FileHandler(log_filename),  # 将日志写入文件
        logging.StreamHandler()  # 也打印到控制台
    ]
)

zkem = win32com.client.Dispatch("zkemkeeper.ZKEM")


devices = [
    {"ip": "192.168.4.2",  "device_id": 1},
    {"ip": "192.168.0.51", "device_id": 1},
    {"ip": "192.168.0.52", "device_id": 2},
    {"ip": "192.168.0.53", "device_id": 3},
    {"ip": "192.168.0.54", "device_id": 4},
    {"ip": "192.168.0.55", "device_id": 5},
    {"ip": "192.168.0.56", "device_id": 6},
    {"ip": "192.168.0.57", "device_id": 7}
]

# devices = [
#     {"ip": "192.168.0.64",  "device_id": 14},
#     {"ip": "192.168.0.65",  "device_id": 15},
#     {"ip": "192.168.0.66",  "device_id": 16}
# ]

def process_device(ip, machine_num, data_str):
    try:
        if zkem.Connect_Net(ip, Port):
            try:
                result = zkem.DeleteAttlogByTime(machine_num, data_str)
                logging.info(f"设备 {ip} 删除日期{data_str}数据结果: {result}")
            except Exception as ex:
                logging.error(f"处理设备 {ip} 时发生异常(DeleteAttlogByTime):{ex}")
            finally:
                zkem.Disconnect()
        else:
            logging.error(f"连接考勤机失败: {ip}")
            return False
    except Exception as e:
        logging.error(f"处理设备 {ip} 时发生异常(Connect_Net):{e}")
        return False
    return True

    
    

def devicemain(data_str):
    for entry in devices:
        try:
            ip = entry['ip']
            machine_num = entry['device_id']
            print(f"====== 处理设备 {ip} (机器号:{machine_num}) ======")
            process_device(ip, machine_num, data_str)

        except Exception as e:
            print(f"设备操作最终失败: {str(e)}")
        finally:
            time.sleep(DELAY_SECONDS)  # 设备间间隔




def start(data_str):
    # 考勤设备数据删除
    try:
        devicemain(data_str)
    except Exception as e:
        print(f"数据删除失败, 错误: {str(e)}")
        return  # 终止进一步操作



if __name__ == '__main__':

    start('2025-05-05 00:00:00')